package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIDWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIDWorker redisIDWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;
    // seckill脚本
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT =new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    // 初始化类之后立马执行
    @PostConstruct
    public void init() {
        SECKILL_EXECUTOR.submit(new VoucherOrderTask());
    }
    // 阻塞队列
    //private BlockingDeque<VoucherOrder> orderBlockingDeque=new LinkedBlockingDeque<>(1024*1024);
    // 线程池
    private static final ExecutorService SECKILL_EXECUTOR = Executors.newSingleThreadExecutor();
    // 执行创建订单任务
    private final String queueName="stream.orders";
    private class VoucherOrderTask implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    // 1.从消息队列中获取订单 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    // 2.判断消息是否获取成功
                    if(list==null||list.isEmpty()){
                        // 2.1.获取失败，说明没有消息，继续下一个循环
                        continue;
                    }
                    // 2.2.获取成功，开始下单
                    MapRecord<String, Object, Object> entries = list.get(0);
                    // 3.解析订单
                    Map<Object, Object> value = entries.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value,new VoucherOrder(),true);
                    // 4.创建订单
                    handleVoucherOrder(voucherOrder);
                    // 5.ACK确认
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",entries.getId());
                } catch (Exception e) {
                    log.error("处理订单异常："+e.getMessage());
                    handlePendingList();
                }

            }
        }
    }

    private void handlePendingList() {
        while (true) {
            try {
                // 1.从消息队列中获取订单 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create(queueName, ReadOffset.from("0"))
                );
                // 2.判断消息是否获取成功
                if(list==null||list.isEmpty()){
                    // 2.1.获取失败，说明没有消息，继续下一个循环
                    break;
                }
                // 2.2.获取成功，开始下单
                MapRecord<String, Object, Object> entries = list.get(0);
                // 3.解析订单
                Map<Object, Object> value = entries.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value,new VoucherOrder(),true);
                // 4.创建订单
                handleVoucherOrder(voucherOrder);
                // 5.ACK确认
                stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",entries.getId());
            } catch (Exception e) {
                log.error("处理订单异常："+e.getMessage());
                try {
                    Thread.sleep(20);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }

        }
    }

    private IVoucherOrderService proxy;
    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        // 尝试获取锁
        //SimpleLock simpleLock = new SimpleLock("order:" + userId, stringRedisTemplate);
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean isLock = lock.tryLock();
        if (!isLock) {
            log.error("不允许重复获取！");
        }
        // 执行业务
        try {
            proxy.createVoucherOrder(voucherOrder);
        }finally {
            // 释放锁
            lock.unlock();
        }
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        // 1.执行lua脚本
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIDWorker.nextId("order");
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId)
        );
        // 2.判断结果是否为0
        int r = result.intValue();
        if (r!=0){
            // 2.1.否，返回异常信息
            return Result.fail(result==1?"库存不足！":"不可重复购买！");
        }
        // 3.获取代理对象
        // 这里会出现问题，如果直接调用函数是本类的this对象，而不是动态代理对象，会导致事务失效
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        // 4.返回订单id
        return Result.ok(orderId);
    }
    /*@Override
    public Result seckillVoucher(Long voucherId) {
        // 1.执行lua脚本
        Long userId = UserHolder.getUser().getId();
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString()
        );
        // 2.判断结果是否为0
        int r = result.intValue();
        if (r!=0){
            // 2.1.否，返回异常信息
            return Result.fail(result==1?"库存不足！":"不可重复购买！");
        }
        // 2.2.是，将优惠券id，用户id和订单id存入阻塞队列
        // 2.2.1.创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        // 订单id
        long orderId = redisIDWorker.nextId("order");
        voucherOrder.setId(orderId);
        // 用户id
        voucherOrder.setUserId(userId);
        // 优惠券id
        voucherOrder.setVoucherId(voucherId);
        // 2.2.2.将订单存入阻塞队列
        orderBlockingDeque.add(voucherOrder);
        // 4.获取代理对象
        // 这里会出现问题，如果直接调用函数是本类的this对象，而不是动态代理对象，会导致事务失效
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        // 3.返回订单id
        return Result.ok(orderId);
    }
*/

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        int count= query()
                .eq("user_id", userId)
                .eq("voucher_id", voucherOrder.getVoucherId())
                .count();
        // 判断订单是否存在
        if(count>0){
            // 存在则返回异常
            return ;
        }
        // 6.不存在，扣减库存
        boolean success = seckillVoucherService
                .update()
                .setSql("stock=stock-1")
                .eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock", 0)
                .update();
        if (!success) {
            log.error("库存不足！");
        }
        save(voucherOrder);
    }
    /*@Override
    public Result seckillVoucher(Long voucherId) {
        // 1.查询优惠券信息
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        // 2.判断秒杀是否开始
        if(LocalDateTime.now().isBefore(voucher.getBeginTime())){
            return Result.fail("秒杀活动尚未开始！");
        }
        // 3.判断秒杀是否过期
        if(LocalDateTime.now().isAfter(voucher.getEndTime())){
            return Result.fail("秒杀活动已结束！");
        }
        // 4.判断是否库存充足
        if (voucher.getStock()<1) {
            return Result.fail("库存不足！");
        }
        // 尝试直接锁住整个函数，但是所有请求都共用一个锁，导致性能低下，只能逐个获取
        // 如果在函数内调用悲观锁，有可能出现该事务未提交，其它线程请求，出现一个用户可以获取多个代金券
        // 应当在主函数中调用该方法的时侯加锁
        // 5.根据优惠券id和用户id查询订单
        Long userId = UserHolder.getUser().getId();
        // 6.尝试获取锁
        //SimpleLock simpleLock = new SimpleLock("order:" + userId, stringRedisTemplate);
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean isLock = lock.tryLock();
        if (!isLock) {
            Result.fail("不允许重复获取！");
        }
        // 7.执行业务
        try {
            // 这里会出现问题，如果直接调用函数是本类的this对象，而不是动态代理对象，会导致事务失效
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        }finally {
            // 释放锁
            lock.unlock();
        }
    }*/
    // Ctrl+Alt+m自动对选中模块封装成函数

    /*@Transactional
    public Result createVoucherOrder(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        int count= query()
                .eq("user_id", userId)
                .eq("voucher_id", voucherId)
                .count();
        // 判断订单是否存在
        if(count>0){
            // 存在则返回异常
            return Result.fail("已获得代金券！");
        }
        // 6.不存在，扣减库存
        boolean success = seckillVoucherService
                .update()
                .setSql("stock=stock-1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0)
                .update();
        if (!success) {
            return Result.fail("库存不足！");
        }
        // 7.创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        // 7.1.订单id
        long orderId = redisIDWorker.nextId("order");
        voucherOrder.setId(orderId);
        // 7.2.用户id
        voucherOrder.setUserId(userId);
        // 7.3.优惠券id
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);
        // 8.返回订单id
        return Result.ok(orderId);
    }*/
}
